package apps.softtech.fastmarket;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;



import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import apps.softtech.Utility.ApplicationConstants;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.fastmarket.adapter.AdapterChat;
import apps.softtech.fastmarket.model.ChatLog;
import apps.softtech.fastmarket.model.DatabaseHandler;
import android.support.v4.widget.SwipeRefreshLayout;

public class ActivityChat extends Activity{
	/**
	 * id to chat
	 */
	int idUserChat;
	/**
	 * listview
	 */
	ListView lvListChat;
	/**
	 * adapter list chat
	 */
	AdapterChat mAdapterChat;
	/**
	 * swipelayout
	 */
	SwipeRefreshLayout mSwipeRefreshLayout; 
	/**
	 * button send
	 */
	Button btSendsms;
	/**
	 * editext content sms
	 */
	EditText etSmsContent;
	/**
	 * content sms
	 */
	String mSmsContent;
	/**
	 * List content chat
	 */
	ArrayList<ChatLog> mChat_Lists = new ArrayList<ChatLog>();
	/**
	 * get list chat from data
	 */
	ArrayList<ChatLog> mChatLogsArrayList = new ArrayList<ChatLog>();
	/**
	 * data handler
	 */
	DatabaseHandler dbh;
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat_in);
		//init data
		dbh = new DatabaseHandler(this);
		
		mChatLogsArrayList = (ArrayList<ChatLog>) dbh.getChatLog(null, null, null, null, null);
		//get intent id user
		Intent inGetId = getIntent();
		if(inGetId!=null){
			if(mChatLogsArrayList.size()==0||mChatLogsArrayList==null){
				return;
			}
			idUserChat = Integer.parseInt(inGetId.getStringExtra("idfromuser"));
			mChat_Lists.clear();
			for (int i = 0; i < mChatLogsArrayList.size(); i++) {
				if (idUserChat==mChatLogsArrayList.get(i).getFromUserId()) {
					//
					// add data to list chat
					//
					ChatLog chatLog = new ChatLog();
					chatLog.setContent(mChatLogsArrayList.get(i).getContent());
					chatLog.setCreatedDate(mChatLogsArrayList.get(i).getCreatedDate());
					chatLog.setFromUserId(mChatLogsArrayList.get(i).getFromUserId());
					chatLog.setToUserId(mChatLogsArrayList.get(i).getToUserId());
					chatLog.setType(mChatLogsArrayList.get(i).getType());
					mChat_Lists.add(chatLog);
				}
			}
			mAdapterChat = new AdapterChat(ActivityChat.this,mChat_Lists);
			lvListChat.setAdapter(mAdapterChat);
			lvListChat.setSelection(mChat_Lists.size()-1);
		}
		//
		//test register sms
		//
		registerReceiver(mBroadcastReceiver, new IntentFilter(ApplicationConstants.RECEIVER_SMS));
		//init  com.receiver.gcm.ok
		lvListChat =(ListView) findViewById(R.id.lvListChat);
		btSendsms = (Button)findViewById(R.id.btSendSms);
		etSmsContent = (EditText)findViewById(R.id.etSmsContent);
		mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
		//
		//set onclick
		//
        //swipeview
		mSwipeRefreshLayout.setColorScheme(android.R.color.holo_blue_dark,
        		android.R.color.holo_blue_light,
        		android.R.color.holo_green_light, android.R.color.holo_green_light);
		mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
            	mSwipeRefreshLayout.setRefreshing(true);
                
               
                ( new Handler()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                         adapter = new AdapterSwipe(getApplicationContext(), item);
//                         lv.setAdapter(adapter);
                    	mSwipeRefreshLayout.setRefreshing(false);
     
                    }
                }, 3000);
            }
        });
		//
		//send sms
		//
		
		btSendsms.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mSmsContent = etSmsContent.getText().toString().trim();
				if (mSmsContent.equals("")||mSmsContent.equals(null)) {
					Log.v("content", " null");
				}else{
					//insert to data
					dbh.insertChatLog(new ChatLog(mSmsContent
							, toDay(), ApplicationConstants.MY_USER, idUserChat, 3));
					//chat
					mChat_Lists.add(new ChatLog(mSmsContent,toDay(),ApplicationConstants.MY_USER,idUserChat,3));
					mAdapterChat = new AdapterChat(ActivityChat.this,mChat_Lists);
					lvListChat.setAdapter(mAdapterChat);
					lvListChat.setSelection(mChat_Lists.size()-1);
					//save list chat
					
					new AsystaskSendSms().execute();
				}
				etSmsContent.setText("");
			}
		});
		//add mListChat
		//
		//
		
		//init adapter
		mAdapterChat = new AdapterChat(ActivityChat.this, mChat_Lists);
		lvListChat.setAdapter(mAdapterChat);
		//
		// mSwipeRefreshLayout to refresh
		//
		//
		//
		//
		lvListChat.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				
			}
			@Override
			public void onScroll(AbsListView arg0, int first, int visible, int total) {
				
			}
		});
		
	}
	/**
	 * send sms
	 */
	class AsystaskSendSms extends AsyncTask<Void, Void, Void>{
		List<NameValuePair> mList;
		HttpRequest mHttpRequest;
		String url="";
		@Override
		protected void onPreExecute() {
			 mHttpRequest = new HttpRequest();
			mList = new ArrayList<NameValuePair>();
			url=ApplicationConstants.BASE_URL+"gcmusers/submit_chat";
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
//			Toast.makeText(ActivityChat.this, ""+Constants.REG_ID, Toast.LENGTH_LONG).show();
			mList.add(new BasicNameValuePair("data",addDataJson().toString()));
			Log.v("", mList.toString());
			mHttpRequest.makeServiceCall(url, mHttpRequest.POST, mList);
			return null;
		}
		/**
		 * add data to send server
		 */
		private JSONObject addDataJson(){
			JSONObject mJsonObject = new JSONObject();
			try{
			mJsonObject.put("st_GcmId",ApplicationConstants.RED_ID);
			mJsonObject.put("st_ToUserId", idUserChat);
			mJsonObject.put("message", mSmsContent);
			}catch (Exception e) {
			}
			return mJsonObject;
		}
		
	}
	/**
	 * Today
	 * @return
	 */
	private String toDay(){
		Calendar c = Calendar.getInstance();
 		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
 		String formattedDate = df.format(c.getTime());
 		 return formattedDate;
	}
	BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle exBundle = intent.getExtras();
			if(exBundle!=null){
				String data = exBundle.getString("data");
				int idFromUser = exBundle.getInt("idfromuser");
				int toUserId = exBundle.getInt("idtouser");
					if(mChat_Lists.size()==0||mChat_Lists==null){
						mChat_Lists.add(new ChatLog(data
								, toDay(), idFromUser, toUserId, 3));
						mAdapterChat = new AdapterChat(context,mChat_Lists);
						lvListChat.setAdapter(mAdapterChat);
					}else{
						mChat_Lists.add(new ChatLog(data
								, toDay(), idFromUser, toUserId, 3));
					mAdapterChat.updateData(mChat_Lists);
				}
			}
		}
	};
	

}
